<template>
  <div class="serviceNoManage">
   <configCompositionTwoWindowStyle
   :leftWidth = "16"
   :rightWidth="8"
   >
      <template slot="card">
        <search
          ref="search1"
          @active="active"
          @advSearch="advSearch"
          :forCall="true"
          :inputTitle="$t('channelsettings.serviceNumber1')"
          :loading="tableLoading"
          @add="addService"
          @refresh="refresh"
          @search="searchByName"
          @turnPage="turnPage"
          @removeBadge="removeBadge"
          @roloadIvrSucc="roloadIvrSucc"
          :currentPage="currentPage"
          :count="count"
          :reload="reload"
          :pageSize="pageSize">
        </search>
        <diyTable :tableHeader="tableHeader" :tableData="tableData" @updata="updata" @del="del" :loading="tableLoading"></diyTable>
      </template>
      <template slot="detail">
        <BreadCrumbConfig v-if="isShowAddOrEdit" :titleArr="titleArr" @back="cancle"></BreadCrumbConfig>
        <div>
          <editService v-if="isShowEdit"
                       :serviceInfo="serviceInfo"
                       @editRefresh="editRefresh"></editService>
        </div>
        <div>
          <add-service v-if="isShowAdd"
            :availableService = "availableService"
            @addRefresh="addRefresh"></add-service>
        </div>
      </template>
    </configCompositionTwoWindowStyle>
  </div>
</template>
<script>
  import configCompositionTwoWindowStyle from '../../../../ui-modules/config/configCompositionTwoWindowStyle'
  import search from '../base/search'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/BreadCrumbConfig'
  import diyTable from '../base/diyTable'
  import editService from '../base/editService.vue'
  import {deepClone, ivrSearch} from '@/utils/m7Utils'
  import AddService from '../base/addService'
  export default {
    name: 'serviceNoManage',
    data () {
      return {
        norSearch: [],
        serviceList: [],
        titleArr: [this.$t('channelsettings.serviceNumber2'), this.$t('channelsettings.serviceNumber3')],
        reload: true,
        isShowAdd: false,
        isShowEdit: false,
        advSearchData: {
          items: [
            {
              title: '服务号类型',
              type: 'select',
              valueName: 'Type',
              data: [
                {label: '普通', value: 'normal'},
                {label: '轻量级', value: 'lightweight'}
              ]
            },
            {
              title: '服务号',
              type: 'input',
              valueName: 'Exten'
            }
          ],
          form: {Type: '', Exten: ''}
        },
        availableService: [],
        dataList: [],
        count: 0,
        pageSize: 10,
        agents: [],
        operFlag: '',
        currPBX: '',
        currentPage: 1,    //   当前页
        tableHeader: [
          {prop: 'Exten', label: this.$t('channelsettings.ServiceNumber')},
          {prop: 'typeName', label: this.$t('channelsettings.serviceNumber5')},
          {prop: 'DisplayName', label: this.$t('channelsettings.serviceNumber8')},
          {prop: 'UpdateTime', label: this.$t('channelsettings.serviceNumber18')},
          {prop: 'PBX', label: 'PBX'},
          {prop: '', label: this.$t('public.operate')}
        ],                        //   自定义 表头
        tableData: [],           //  表格数据
        tableLoading: false,      //   表格  loading
        isShowAddOrEdit: false,   //   右侧  新建或修改 显隐
        inputName: '',
        serviceInfo: {}
      }
    },
    components: {
      AddService,
      configCompositionTwoWindowStyle,
      search,
      BreadCrumbConfig,
      diyTable,
      editService
    },
    methods: {
      cancle () {
        this.isShowAdd = false
        this.isShowEdit = false
        this.isShowAddOrEdit = false
      },
      removeBadge () {
        this.operFlag = ''
        this.$refs.search1.advSearch2()
      },
      active () {},
//      高级搜索
      advSearch (val, flag, deleteFlag) {
        if (this.operFlag === 'add' && !deleteFlag) { // 添加回到第一页，编辑回到当前页
          this.currentPage = 1
        }
        this.inputName = ''
        let data = {}
        this.isShowAdd = false
        this.isShowEdit = false
        this.isShowAddOrEdit = false
        data.Account = this.$store.state.session.account.account
        val.serviceType && (data.Type = val.serviceType)
        val.serviceNo && (data.Exten = val.serviceNo)
        val.PBX && (data.PBX = val.PBX)
        if (!flag) {
          this.operFlag = ''
        }
        this.search(data, deleteFlag)
      },
//      添加服务号
      addService () {
        this.isShowAddOrEdit = true
        this.isShowAdd = true
        this.isShowEdit = false
        this.titleArr = [this.$t('channelsettings.serviceNumber2'), this.$t('channelsettings.serviceNumber3')]
        this.availableService = deepClone(this.serviceList)
//        let pbx = this.$store.state.session.user.pbx
//        if (this.$store.state.session.ivrMap[pbx]) {
//          let _service = deepClone(this.$store.state.session.ivrMap[pbx].data.ivr_available_service_no)
//          _service.forEach(item => {
//            this.availableService.push(item._id)
//          })
//        } else {
//          let data = {}
//          data.Account = this.$store.state.session.account.account
//          data.PBX = pbx
//          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
//            let _service = deepClone(this.$store.state.session.ivrMap[pbx].data.ivr_available_service_no)
//            _service.forEach(item => {
//              this.availableService.push(item._id)
//            })
//          })
//        }
      },
//      添加服务号成功刷新
      addRefresh (data) {
        this.reload = false
        let _index = 0
        this.serviceList.forEach((item, index) => {
          if (item === data.Exten) {
            _index = index
          }
        })
        this.serviceList.splice(_index, 1)
        this.isShowAdd = false
        this.isShowAddOrEdit = false
        this.operFlag = 'add'
        console.log(data)
        this.currPBX = data.PBX
        this.$refs.search1.advSearch1()
      },
      roloadIvrSucc () {
        this.reload = true
      },
      editRefresh (data) {
        this.reload = false
        this.operFlag = 'edit'
        this.currPBX = data.PBX
        this.inputName = ''
        this.isShowAdd = false
        this.isShowEdit = false
        this.isShowAddOrEdit = false
        this.$refs.search1.advSearch1()
      },
//      刷新
      refresh () {
        // this.currentPage = 1
        this.inputName = ''
        this.isShowAdd = false
        this.isShowEdit = false
        this.isShowAddOrEdit = false
        this.operFlag = ''
        this.$refs.search1.advSearch2()
      },
//      input 搜索
      searchByName (val) {
        console.log(val)
        this.isShowAdd = false
        this.isShowEdit = false
        this.isShowAddOrEdit = false
        this.inputName = val
        this.currentPage = 1
        this.norSearch = ivrSearch(this.dataList, val, ['Exten', 'DisplayName'])
        this.count = this.norSearch.length
        this.tableData = []
        this.handleFakePage(this.norSearch)
//        this.search()
      },
//      初始化数据
      search (data1, deleteFlag) {
        this.tableData = []
        this.dataList = []
        let _pageArray = []
        this.tableLoading = true
        this.$store.dispatch('queryServiceNo', data1).then((res) => {
          if (res.success) {
            if (res.list) {
              const lastPage = Math.ceil(res.list.length / 10)
              if (deleteFlag && this.currentPage >= lastPage) {
                this.currentPage = lastPage
              }
              this.tableData = []
              this.count = res.list.length
              if (this.count) {
                let _data = res.list.filter((item) => {
                  return (item.PBX === this.currPBX)
                })
                if (this.operFlag === 'add' || this.operFlag === 'edit' || this.operFlag === 'del') {
                  this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.currPBX, typeName: 'ivr_service_no', data: _data || [], flag: 'data', node: this})
                }
                res.list.forEach(item => {
                  if (item.Type === 'normal') {
                    let obj = {
                      typeName: this.$t('channelsettings.serviceNumber6'),
                      Account: item.Account,
                      DisplayName: item.DisplayName,
                      Exten: item.Exten,
                      PBX: item.PBX,
                      Schedules: item.Schedules,
                      ToPeer: item.ToPeer,
                      Type: item.Type,
                      UpdateTime: item.UpdateTime,
                      UpdateUser: item.UpdateUser,
                      _id: item._id
                    }
                    _pageArray.push(obj)
                  } else {
                    let objL = {
                      typeName: this.$t('channelsettings.serviceNumber7'),
                      Account: item.Account,
                      DisplayName: item.DisplayName,
                      Exten: item.Exten,
                      PBX: item.PBX,
                      Schedules: item.Schedules,
                      ToPeer: item.ToPeer,
                      Type: item.Type,
                      UpdateTime: item.UpdateTime,
                      UpdateUser: item.UpdateUser,
                      _id: item._id,
                      ToPeerType: item.ToPeerType,
                      IvrProcessId: item.IvrProcessId
                    }
                    _pageArray.push(objL)
                  }
                })
                this.dataList = []
                this.handleFakePage(_pageArray)
                this.dataList = deepClone(_pageArray)
              }
            }
            this.tableLoading = false
//            this.isShowAddOrEdit = false
          }
        })
      },
      handleFakePage (_array) {
        for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < _array.length; i++) {
          this.tableData.push(_array[i])
        }
      },
      turnPage (val) {
        this.currentPage = val
        this.operFlag = ''
        this.tableData = []
        if (this.inputName !== '') {
          this.handleFakePage(this.norSearch)
        } else {
          this.handleFakePage(this.dataList)
        }
//        this.search({Account: this.$store.state.session.account.account})
      },
//      修改服务号
      updata (val) {
        this.isShowAddOrEdit = true
        this.isShowAdd = false
        this.titleArr = [this.$t('channelsettings.serviceNumber2'), this.$t('channelsettings.serviceNumber17')]
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[val.PBX]) {
          this.serviceInfo = val
          this.isShowEdit = true
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = val.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            if (res.success) {
              this.serviceInfo = val
              this.isShowEdit = true
            }
          })
        }
      },
//      删除服务号
      del (val) {
        let data = {}
        if (val.Type === 'normal') {
          data = {
            Account: val.Account,
            PBX: val.PBX,
            _id: val._id,
            Type: val.Type,
            Exten: val.Exten,
            DisplayName: val.DisplayName
          }
        } else {
          data = {
            Account: val.Account,
            PBX: val.PBX,
            _id: val._id,
            Type: val.Type,
            Exten: val.Exten,
            DisplayName: val.DisplayName,
            ToPeer: val.ToPeer,
            ToPeerType: val.ToPeerType,
            IvrProcessId: val.IvrProcessId
          }
        }
        this.$confirm(this.$t('channelsettings.serviceNumber19'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteServiceNo', data).then(res => {
            if (res.success) {
              this.operFlag = 'del'
              this.currPBX = data.PBX
              this.$refs.search1.advSearch1('delete')
              this.serviceList.push(val.Exten)
              this.isShowAdd = false
              this.isShowEdit = false
              this.isShowAddOrEdit = false
              this.reload = false
              this.$message({
                message: this.$t('channelsettings.serviceNumber20'),
                type: 'success'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      }
    },
    mounted () {
    },
    beforeMount () {
      this.operFlag = ''
      this.currPBX = ''
      this.search({Account: this.$store.state.session.account.account})
      let data = {}
      data.Account = this.$store.state.session.account.account
      data.PBX = this.$store.state.session.user.pbx
      this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
        if (res.success) {
          let _service = deepClone(this.$store.state.session.ivrMap[this.$store.state.session.user.pbx].data.ivr_available_service_no)
          _service.forEach(item => {
            this.serviceList.push(item._id)
          })
        }
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
</style>
